<script setup lang='ts'>
import { useCommunityExport, useCommunityIndex } from '@fl/api/add-elevator-api'
import { useGetCascadeData } from '@fl/api/elevator-api/verify'
import type { historyIndexParam } from '@fl/api/add-elevator-api/model/history-model'
import { SearchForm, SearchTable } from '@fl/components'
import { cloneDeep } from 'lodash-es'
import type { OptionsType, PlusColumn } from 'plus-pro-components'
import { reactive } from 'vue'
import type { VxeGridProps, VxePagerEvents } from 'vxe-table'
import { hasPermi } from '@fl/utils/has-permi'
import addOrEditBox from './component/add-or-edit.vue'

defineOptions({
    // eslint-disable-next-line vue/component-definition-name-casing
    name: 'retrofit-elevator-community-list',
})

const createVisible = ref<boolean>(false)
const editId = ref<string>('')
const currentInfo = ref<any>({})
const records = ref<any>([])

// 搜索条件、分页参数
const initialState = {
    areaCode: '',
    streetCode: '',
    communityName: '',
}
const state = ref<historyIndexParam>(cloneDeep(initialState))
const searchConditions = ref<historyIndexParam>(cloneDeep(initialState))

const tablePage = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0,
})

const getAreaOptionsParams = computed(() => ({
    targetLabel: 'area',
}))
const getStreetOptionsParams = computed(() => ({
    areaCode: state.value.areaCode,
    targetLabel: 'street',
}))
const { data: areaOptions } = useGetCascadeData(getAreaOptionsParams)
const { data: streetOptions } = useGetCascadeData(getStreetOptionsParams, 'areaCode')

watch(() => state.value.areaCode, () => {
    const { building, communityCode, projectId, streetCode, unit, ...data } = state.value
    state.value = cloneDeep(data)
})

watch(() => state.value.streetCode, () => {
    const { building, communityCode, projectId, unit, ...data } = state.value
    state.value = cloneDeep(data)
})

// 查询列表
const params = computed(() => ({
    areaCode: searchConditions.value.areaCode,
    streetCode: searchConditions.value.streetCode,
    communityName: searchConditions.value.communityName,
    pageIndex: tablePage.currentPage,
    pageSize: tablePage.pageSize,
}))
const { data, isLoading } = useCommunityIndex(params)

watchEffect(() => {
    if (data.value) {
        records.value = cloneDeep(data.value.records)
        tablePage.total = data.value.total!
    }
})

// 导出
const exportParams = computed(() => ({
    areaCode: searchConditions.value.areaCode,
    streetCode: searchConditions.value.streetCode,
    communityName: searchConditions.value.communityName,
}))
const { isPending, mutateAsync } = useCommunityExport(exportParams)
async function exportData() {
    const res = await mutateAsync()
    if (res) {
        const objectUrl = URL.createObjectURL(res)
        location.href = objectUrl
        URL.revokeObjectURL(objectUrl)
    }
}

function submit() {
    searchConditions.value = cloneDeep(state.value)
    resetTablePage()
}

function reset() {
    state.value = cloneDeep(initialState)
    searchConditions.value = cloneDeep(initialState)
    resetTablePage()
}

function resetTablePage() {
    tablePage.currentPage = 1
    tablePage.pageSize = 10
}

// 新增
function goToAdd() {
    createVisible.value = true
    editId.value = ''
    currentInfo.value = {}
}

// 列表：编辑
function goToEdit(row: any) {
    createVisible.value = true
    editId.value = String(row.id)
    currentInfo.value = cloneDeep(row)
}

const handlePageChange: VxePagerEvents.PageChange = ({ currentPage, pageSize }) => {
    tablePage.currentPage = currentPage
    tablePage.pageSize = pageSize
}

const columns: PlusColumn[] = [
    {
        colProps: {
            span: 6,
        },
        fieldProps: {
            filterable: true,
        },
        label: '所在区',
        options: areaOptions as OptionsType,
        prop: 'areaCode',
        valueType: 'select',
    },
    {
        colProps: {
            span: 6,
        },
        fieldProps: {
            filterable: true,
        },
        label: '街道',
        options: streetOptions as OptionsType,
        prop: 'streetCode',
        valueType: 'select',
    },
    {
        colProps: {
            span: 6,
        },
        label: '社区',
        prop: 'communityName',
    },
]
const gridOptions = reactive<VxeGridProps>({
    columns: [
        { title: '序号', type: 'seq', width: 60 },
        { field: 'areaName', title: '所在区' },
        { field: 'streetName', title: '街道' },
        { field: 'communityName', title: '社区' },
        { slots: { default: 'operate' }, title: '操作', width: 160 },
    ],
})
</script>

<template>
    <ElCard class="mb-20"
            shadow="never"
    >
        <SearchForm v-model="state"
                    :columns="columns"
                    submit-text="搜索"
                    @reset="reset"
                    @submit="submit"
        />
    </ElCard>

    <ElCard shadow="never">
        <SearchTable v-bind="gridOptions"
                     v-model:pager="tablePage"
                     :loading="isLoading"
                     :data="records"
                     @page-change="handlePageChange"
        >
            <template #toolbar_buttons>
                <ElButton v-if="hasPermi('区属数据-新增')"
                          type="primary"
                          @click="goToAdd"
                >
                    <div class="i-ic:baseline-add size-16" />
                    新增
                </ElButton>

                <ElButton type="primary"
                          plain
                          :loading="isPending"
                          @click="exportData"
                >
                    <div class="i-iconamoon:upload size-16" />
                    导出
                </ElButton>
            </template>

            <template #operate="{ row }">
                <el-button v-if="hasPermi('区属数据-新增')"
                           class="small"
                           type="primary"
                           text
                           @click="goToEdit(row)"
                >
                    编辑
                </el-button>
            </template>
        </SearchTable>
    </ElCard>

    <addOrEditBox v-model:visible="createVisible"
                  v-model:id="editId"
                  v-model:info="currentInfo"
    />
</template>

<style lang="scss" scoped>
:deep(.small.el-button) {
    padding: 4px;
    margin-left: 6px;
}
</style>
